<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入机器人名称" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="交易所" prop="exchangeId">
        <el-select v-model="queryParams.exchangeId" placeholder="请选择交易所" clearable size="small">
          <el-option v-for="item in exchangeOptions" :key="item.name" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="交易对" prop="symbol">
        <el-input v-model="queryParams.symbol" placeholder="请输入交易对" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="策略" prop="strategyId">
        <el-select v-model="queryParams.strategyId" placeholder="请选择策略" clearable size="small">
          <el-option v-for="item in strategyOptions" :key="item.name" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="运行状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
           <el-option v-for="item in statusOptions" :key="item.name" :label="item.name" :value="item.status"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addRobot" v-hasPermi="['trade:robot:save']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="updateRobot" v-hasPermi="['trade:robot:update']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="delRobot" v-hasPermi="['trade:robot:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-video-play" size="mini" :disabled="multiple" @click="startRobot" v-hasPermi="['trade:robot:start']">启动</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-video-pause" size="mini" :disabled="multiple" @click="pauseRobot" v-hasPermi="['trade:robot:pause']">暂停</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="robotList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="id"/>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="交易所" align="center" prop="exchange.name"/>
      <el-table-column label="交易对" align="center" prop="symbol"/>
      <el-table-column label="K线间隔" align="center" prop="timeInterval"/>
      <el-table-column label="策略" align="center" prop="strategy.name"/>
      <el-table-column label="交易金额(U)" align="center" prop="amount"/>
      <el-table-column label="交易滑点(%)" align="center" prop="slip"/>
      <el-table-column label="运行状态" align="center" prop="status" :formatter="stateFormat"/>
      <el-table-column label="订单状态" align="center" prop="orderStatus"/>
      <el-table-column label="创建时间" align="center" prop="createdTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="updateRobot(scope.row)" v-hasPermi="['trade:robot:update']">修改</el-button>
          <el-button size="mini" type="text" con="el-icon-delete" @click="delRobot(scope.row)" v-hasPermi="['trade:robot:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改机器人对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="机器人名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入机器人名称" />
        </el-form-item>
        <el-form-item label="交易所" prop="exchangeId">
          <el-select v-model="form.exchangeId" placeholder="请选择交易所" @change="onExchangeChange" :style="{width: '100%'}">
            <el-option v-for="item in exchangeOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易对" prop="symbol">
          <el-input v-model="form.symbol" placeholder="请输入交易对" />
        </el-form-item>
        <el-form-item label="K线间隔" prop="timeInterval">
          <el-select v-model="form.timeInterval" placeholder="请选择K线间隔" @change="onKLineChange" :style="{width: '100%'}">
            <el-option v-for="item in kLineOptions" :key="item.label" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采用策略" prop="strategyId">
          <el-select v-model="form.strategyId" placeholder="请选择策略" @change="onStrategyChange" :style="{width: '100%'}">
            <el-option v-for="item in strategyOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="CRON表达式" prop="cronExpression">
          <el-input v-model="form.cronExpression" placeholder="请输入CRON表达式" />
        </el-form-item>
        <el-form-item label="交易金额(U)" prop="amount">
          <el-slider :max='1000' :step='1' v-model="form.amount" show-input></el-slider>
        </el-form-item>
        <el-form-item label="交易滑点(%)" prop="slip">
          <el-slider :max='100' :step='1' v-model="form.slip" show-input></el-slider>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { saveRobot, removeRobot, updateRobot, getRobot, searchRobot, startRobot, pauseRobot} from "@/api/trade/robot";
export default {
  name: "Robot",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 机器人表格数据
      robotList: [],
      // 运行状态
      statusOptions: [
        {
          name: '正常',
          status: '0'
        }, {
          name: '暂停',
          status: '1'
        }
      ],
      // k线间隔数据
      kLineOptions: [
        {
          label: '1m',
          value: '1m'
        }, {
          label: '5m',
          value: '5m'
        }, {
          label: '15m',
          value: '15m'
        }, {
          label: '30m',
          value: '30m'
        }, {
          label: '1h',
          value: '1h'
        }, {
          label: '1d',
          value: '1d'
        }
      ],
      // 交易所数据
      exchangeOptions: [],
      // 策略数据
      strategyOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        name: null,
        symbol: null,
        exchangeId: null,
        strategyId: null,
        status: null,
      },
      // 表单参数
      form: {
        id: null,
        name: null,
        exchangeId: null,
        symbol: null,
        timeInterval: null,
        strategyId: null,
        cronExpression: null,
        amount: 0,
        slip: 0,
        status: null,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "机器人名称不能为空", trigger: "blur" }
        ],
        invokeTarget: [
          { required: true, message: "调用目标不能为空", trigger: "blur" }
        ],
        symbol: [
          { required: true, message: "交易对不能为空", trigger: "blur" }
        ],
        timeInterval: [
          { required: true, message: "K线间隔不能为空", trigger: "change" }
        ],
        exchangeId: [
          { required: true, message: "交易所不能为空", trigger: "change" }
        ],
        cronExpression: [
          { required: true, message: "CRON表达式不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "交易金额不能为空", trigger: "blur" }
        ],
        slip: [
          { required: true, message: "交易滑点不能为空", trigger: "blur" }
        ],
        strategyId: [
          { required: true, message: "策略不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getRobot();
    this.getList();
  },
  methods: {
    stateFormat(row, column) {
      if (row.status === '0') {
        return '正常'
      } 
      if (row.status === '1') {
        return '暂停'
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        exchangeId: null,
        symbol: null,
        timeInterval: null,
        strategyId: null,
        cronExpression: null,
        amount: null,
        slip: null,
        status: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 更改交易所
    onExchangeChange(exchangeId) {
        if(this.title == '添加机器人'){
            this.$forceUpdate();
            this.form.exchangeId = exchangeId;
        }
    },
    // 更改K线间隔
    onKLineChange(timeInterval) {
        this.$forceUpdate();
        this.form.timeInterval = timeInterval;
    },
    // 更改策略
    onStrategyChange(strategyId) {
      this.$forceUpdate();
      this.form.strategyId = strategyId;
    },
    // 更改状态
    onStatusChange(id) {
      this.form.status = id;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增机器人 */
    addRobot() {
      this.reset();
      getRobot().then(response => {
        this.exchangeOptions = response.exchanges;
        this.strategyOptions = response.strategies;
        this.open = true;
        this.title = "添加机器人";
      });
    },
    /** 删除机器人 */
    delRobot(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除机器人编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return removeRobot(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 修改机器人 */
    updateRobot(row) {
      this.reset();
      const id = row.id || this.ids;
      getRobot(id).then(response => {
        this.exchangeOptions = response.exchanges;
        this.strategyOptions = response.strategies;
        this.form = response.data;
        this.form.strategyId = response.data.strategy.id;
        this.form.exchangeId = response.data.exchange.id;
        this.form.status = response.data.status;
        this.open = true;
        this.title = "修改机器人";
      });
    },
    /** 查询机器人详情 */
    getRobot() {
      this.loading = true;
      getRobot().then(response => {
        this.exchangeOptions = response.exchanges;
        this.strategyOptions = response.strategies;
      });
    },
    /** 查询机器人列表 */
    getList() {
      this.loading = true;
      searchRobot(this.queryParams).then(response => {
        this.robotList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 启动机器人 */
    startRobot(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认启动机器人编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return startRobot(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("启动成功");
        }).catch(() => {});
    },
    /** 暂停机器人 */
    pauseRobot(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认暂停机器人编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return pauseRobot(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("暂停成功");
        }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRobot(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            saveRobot(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    }
  }
};
</script>